package com.blue.gateway.config.filters.global;

import cn.hutool.http.HttpStatus;
import com.blue.common.enums.ServiceEnum;
import com.blue.common.exception.BaseException;
import com.blue.gateway.bean.constants.GatewayHeaderKey;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 执行器链说明：order顺序最好比-1小，不要大于0，否则异常抛出后，存在无法被异常处理器捕获的情况，越小的越先执行
 * 1.格式校验过滤器
 *
 * @author liulei
 * @version 1.0
 */
@Slf4j
@Configuration
public class ValidateRequestFormatFilter extends AbstractGatewayFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("1.过滤器链-格式校验，对请求进行格式校验");
        if (this.isIgnoreUrl(exchange)) {
            log.info("该请求属于忽略类型url，此处不检测Header");
            return chain.filter(exchange);
        }
        ServerHttpRequest.Builder builder = exchange.getRequest().mutate();
        ServerHttpRequest request = builder.build();
        String scope = request.getHeaders().getFirst(GatewayHeaderKey.SCOPE);
        List<Integer> scopeList = Arrays.stream(ServiceEnum.values()).map(ServiceEnum::getCode).collect(Collectors.toList());
        if (StringUtils.isEmpty(scope) || !scopeList.contains(Integer.valueOf(scope))) {
            log.error("请求格式错误，缺少Header：scope");
            throw new BaseException(HttpStatus.HTTP_BAD_REQUEST, "非法请求，请检查请求类型及参数");
        }
        // 解析token后添加相关header信息
        ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate()
                .header(GatewayHeaderKey.SCOPE, scope)
                .build();
        return chain.filter(exchange.mutate().request(serverHttpRequest).build());
    }

    @Override
    public int getOrder() {
        return -100;
    }
}
